package com.qin.controller.root;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.qin.entity.Book;
import com.qin.service.BookService;
import com.qin.service.impl.BookServiceImpl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;

/**
 * 处理提交的图书id和图书文件
 */
@WebServlet("/commitBookfile")
public class CommitBookFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private BookService bookService = new BookServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * 想法是：拿到图书的id和对应的文件，
	 * 把文件放在当前项目的WEB-INF/bookfile下，然后修改数据库中的记录，那对应的路径放上去
	 * 然后发送邮件只要去查对应路径，直接io操作就可以完成
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		// 先判断前台是否有multipart属性
		if(isMultipart) {
			FileItemFactory factory = new  DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			try {
				// 解析前台传过来的所有字段,然后保存到items中
				List<FileItem> items = upload.parseRequest(request);

				// 图书id
				Long bookId = null;
				
				// 遍历item中的数据
				Iterator<FileItem> iterator = items.iterator();
				while(iterator.hasNext()) {
					FileItem item = iterator.next();
					// 判断是否是普通form表单字段
					if(item.isFormField()) {
						if(StrUtil.equals(item.getFieldName(), "bookId")){ // 通过name判断
							bookId = Long.parseLong(item.getString("utf-8"));
						}else {
							System.out.println("其他普通字段上传");
						}
						
					}else { // 文件上传
						if(StrUtil.equals(item.getFieldName(), "bookFile")) {
							// 拿到文件名字
							String fileName = item.getName();
							// 拿到文件路径
							String projectPath = request.getSession().getServletContext().getRealPath("/");
							String tomcatPath = new File(projectPath).getParentFile().getParentFile().getParentFile().getAbsolutePath();
						
							File file = new File(tomcatPath+"/upload",fileName);
							try {
								// 开始上传
								item.write(file);
								// 然后把这个文件的地址放入到数据库中
								Book book = new Book();
								book.setFileUrl(file.getAbsolutePath());
								// 修改
								bookService.updateBook(bookId, book);
								
								StaticLog.debug("文件{}上传成功！", fileName);
								// 最后重定向到当前页
								response.sendRedirect(request.getContextPath()+"/WEB-INF/root/root/jsp");
							} catch (Exception e) {
								e.printStackTrace();
							}
						}else { 
							// ???
							System.out.println("其他文件字段上传");
						}
					}
				}
				
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
		
	}

}
